﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CubeDAL;
using SysInfo;

namespace CrossQuery.ConditionQuery
{
    public class ConditionalQuery : Query
    {
        private string database_name, table_name;
        private string[] output_fields;
        private List<Condition> condition_list;

        public ConditionalQuery(string database, string table, string[] output_fields)
        {
            this.database_name = database;
            this.table_name = table;
            this.output_fields = output_fields;
            condition_list = new List<Condition>();
        }

        public string[] OutputFields 
        {
            get { return output_fields; }
            set { output_fields = value; }
        }

        public void AddCondition(Condition condition)
        {
            condition_list.Add(condition);
        }

        public bool RemoveCondition(Condition condition)
        {
            return condition_list.Remove(condition);
        }

        public List<List<String>> Execute() 
        {
            MySQLWrapper wrapper = new MySQLWrapper(Constant.DB_SERVER, database_name, Constant.DB_USER, Constant.DB_PASSWORD);
            return wrapper.Select(ToSQLCommand(), output_fields);
        }

        public string ToSQLCommand()
        {
            if (output_fields == null || output_fields.Length == 0)
                return "SELECT '未指定输出字段'";
            StringBuilder sb = new StringBuilder();
            sb.Append("SELECT `").Append(output_fields[0]).Append("`");
            for (int i = 1; i < output_fields.Length; ++i)
            {
                sb.Append(", `").Append(output_fields[i]).Append("`");
            }
            sb.Append(" FROM `").Append(database_name).Append("`.`").Append(table_name).Append("` ");
            if (condition_list.Count > 0) {
                sb.Append(" WHERE TRUE ");
                foreach (Condition cond in condition_list)
                {
                    sb.Append(" \nAND (").Append(cond.ToSQLString()).Append(")");
                }
            }
            sb.Append(";");
            return sb.ToString();
        }
    }
}
